package com.itheima.controller;

import com.itheima.pojo.ResultInfo;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.HeiMaUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    @ResponseBody
    public ResultInfo login(@RequestBody Map<String, String> params, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("提交的数据: " + params);
        // 获取用户名和密码
        String username = params.get("username");
        String password = params.get("password");
        // 调用业务层实现登录
        User user = userService.login(username, password);
        // 创建结果对象
        ResultInfo resultInfo;

        if (user != null) {
            HttpSession session = request.getSession();

            session.setAttribute("user", user);
            resultInfo = new ResultInfo(true, "登录成功", user);

            // 解决CSRF: 不让B网站页面携带用户Cookie访问Web服务器(A)
            // javax.servlet.http.Cookie; 没有设置samesite属性
            // HeiMaUtils.sendLoginSameSiteCookie(session, response);
        } else {
            resultInfo = new ResultInfo(false, "用户名或密码错误");
        }
        return resultInfo;
    }

    @RequestMapping("/register")
    @ResponseBody
    public ResultInfo register(@RequestBody Map<String, String> params) {

        System.out.println("提交的数据: " + params);
        // 获取用户名和密码
        String username = params.get("username");
        String password = params.get("password");
        String telephone = params.get("telephone");
        // 调用业务层实现登录
        int count = userService.register(username, password, telephone);
        // 创建结果对象
        ResultInfo resultInfo;

        if (count > 0) {
            resultInfo = new ResultInfo(true, "注册成功");
        } else {
            resultInfo = new ResultInfo(false, "注册失败");
        }
        return resultInfo;
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        log.warn("退出登陆,销毁session");

        return "redirect:/goods/list";
    }


    @RequestMapping("/test02")
    public String test02(String from, HttpServletRequest request) {
        log.debug("from2 = " + from);
        request.setAttribute("from", from);
        return "test2"; // 模板名字
    }
}
